# encoding:utf-8
from django.shortcuts import render,render_to_response
from django.template import Context
from django.template.loader import get_template
from django.http import HttpResponse,HttpResponseRedirect,HttpResponseBadRequest,Http404
from django.template import RequestContext
from forums.forms import MyCreateUserForm
from django.views.generic import View,TemplateView,ListView,DetailView
from django.views.decorators.csrf import csrf_exempt,requires_csrf_token
from django.contrib.auth import authenticate,backends,get_user
from django.contrib import auth
from django.contrib.auth.models import User
import json
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from .forms import QuestionForm
from .models import *
from django.db.models.signals import post_save
from notifications import notify

# Create your views here.

def index(request):
    template_name = 'forums/index.html'
    if request.method =='GET':
        allquestion = Question.objects.all().order_by('-id')
        user = UserProfile.objects.all()
        user_list = []
        for u in user:
            n = len(Question.objects.filter(questioner = u))
            user_list.append((u.name,n))
        usergroup = sorted(user_list,key=lambda x:x[1],reverse=True)
        return render(request,template_name,{'allquestion':allquestion,'usergroup':[x for x in usergroup]},)
    template = get_template(template_name)
    html = template.render(RequestContext(request,{'name':'hello'}))
    return HttpResponse(html)


@requires_csrf_token
def register(request):
    # password2 = 'jn691121'
    password2  = request.POST.get('password')
    template_name = 'forums/register.html'
    if request.method == 'POST':
        data = request.POST.copy()
        data['password2'] = password2
        print(data)
        form = MyCreateUserForm(data)
        if form.is_valid():
            inst = form.save()
            # user = authenticate(username=request.POST.get('username'), password=request.POST.get('password'))
            # login(request,user)
            return HttpResponseRedirect('/')
        else:
            print(form._errors)
            # return render(request,template_name,{'form':form})
            return HttpResponseRedirect('/account/register/')
    else:
        return render(request,template_name)

@requires_csrf_token
def login(request):
        template_name = 'forums/login.html'
        if request.method == 'POST':
            username = request.POST.get("username","")
            password = request.POST.get("password","")
            user = auth.authenticate(username=username,password=password)

            errors = []

            if user is not None:
                auth.login(request, user)
                return HttpResponseRedirect('/')
            else:
                errors.append("密码或者用户名不正确")

            mydict = {"errors":errors}

            return HttpResponseBadRequest(json.dumps(mydict),content_type="application/json")
        else:
            return render(request,template_name)

#用户扩展信息
@login_required()
def userprofile(request):
    template_name = 'forums/pcenter.html'
    if request.method == 'POST':
        avatar = request.POST.get('avatar',False)
        name   = request.POST.get('name',False)
        age    = request.POST.get('age',False)
        telphone = request.POST.get('telphone',False)
        address  = request.POST.get('address',False)
        website  = request.POST.get('website',False)
        birthday = request.POST.get('birthday',False)
        gender   = request.POST.get('gender',False)
        userid = request.user.id
        userprofile = get_object_or_404(User,id = userid)
        p = userprofile.get_profile()
        p.update(avatar = avatar,name = name,age=age,telphone = telphone,address = address,website = website,birthday=birthday,gender=gender)
        p.save()
        template = get_template(template_name)
        html = template.render(RequestContext(request,{'userinfo':'hello'}))
        return HttpResponse(html)
    else:
        template = get_template(template_name)
        html = template.render(RequestContext(request,{'userinfo':'hello'}))
        return HttpResponse(html)

@login_required()
def userinfo(request):
    template_name = 'forums/userinfo.html'
    template = get_template(template_name)
    html = template.render(RequestContext(request,{'userinfo':'hello'}))
    return HttpResponse(html)

@login_required()
@requires_csrf_token
def publish(request):
    template_name = 'forums/publish.html'
    if request.method == 'POST':
        print(request.user.id)
        questioner = get_object_or_404(UserProfile,user = request.user)
        # data = request.POST.copy()
        questioner = questioner
        # print(data)

        if request.POST.get('title'):
            title = request.POST.get('title')
        if request.POST.get('content'):
            content = request.POST.get('content')
        question = Question(title=title,content=content,questioner = questioner)
        question.save()
        return HttpResponseRedirect('/')
        # return render(request,template_name,{'form':'sss'})


        # f = QuestionForm(data)
        # if f.is_valid():
        #     f.save()
        #     return HttpResponseRedirect('/')
        # print f.errors
        # return render(request,template_name,{'form':f})
    else:
        form = QuestionForm()
        return render(request,template_name,{'form':form})
        # template = get_template(template_name)
        # html = template.render(RequestContext(request,{'form':form}))
        # return HttpResponse(html)

def comment(request,id):
    template_name = 'forums/question_comments.html'
    if request.method == 'GET':
        content = Question.objects.filter(id = id)
        return render(request,template_name,{'content':content})
    template = get_template(template_name)
    html = template.render(RequestContext(request,{'form':'hello'}))
    return HttpResponse(html)

def resume(request):
    template_name ='forums/myresume.html'
    if request.method == 'GET':
        return render(request,template_name)
    template = get_template(template_name)
    html = template.render(RequestContext(request,{'form':'hello'}))
    return HttpResponse(html)

def notify_publish(sender,instance,created,**kwargs):
    notify.send(instance,recipient = get_object_or_404(User,id=7),verb = 'was saved')
post_save.connect(notify_publish,sender=Question)

def timeaxis(request):
    template_name = 'forums/time-index.html'
    if request.method == 'GET':
        return render(request,template_name)

def friendship(request):
    template_name = 'forums/friendship.html'
    if request.method == 'GET':
        return render(request,template_name)








